<?php
/**
* @version 1.3.0
* @package RSform!Pro 1.3.0
* @copyright (C) 2007-2010 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgSystemRSMail_RSFormPro_Subscription extends JPlugin
{
	function plgSystemRSMail_RSFormPro_Subscription( &$subject, $config )
	{
		//Call the parent constructor
		parent::__construct( $subject, $config );
		
		//Get a reference to this plugin
		$this->_plugin =& JPluginHelper::getPlugin( 'system', 'rsmail_rsformpro_subscription' );
	}
	
	function canRun()
	{
		if (class_exists('RSFormProHelper')) return true;
		$helper = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_rsform'.DS.'helpers'.DS.'rsform.php';
		if (file_exists($helper))
		{
			require_once($helper);
			return true;
		}
		
		return false;
	}
	
	function is16()
	{
		$jversion = new JVersion();
		$current_version =  $jversion->getShortVersion();
		return (version_compare('1.6.0', $current_version) <= 0);
	}
	
	function rsfp_f_onAfterStoreSubmissions($args)
	{
		// Load the language file
		$lang =& JFactory::getLanguage();
		$lang->load('com_rsmail', JPATH_ADMINISTRATOR );
		$lang->load('com_rsmail', JPATH_SITE);
		
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
		$lang =& JFactory::getLanguage();
		$config =& JFactory::getConfig();
		
		$userid = $user->id;
		
		// Load the language file
		$lang->load('com_rsmail', JPATH_ADMINISTRATOR );
		$lang->load('com_rsmail', JPATH_SITE);
		$tag = $lang->getTag();
		
		$db->setQuery("SELECT IdList , params FROM #__rsmail_integrations WHERE IntegrationType = 'rsfp'");
		$details = $db->loadObjectList();
		
		if (!empty($details))
		foreach ($details as $detail)
		{
			$reg =& JRegistry::getInstance('');
			if (plgSystemRSMail_RSFormPro_Subscription::is16())
				$reg->loadJSON($detail->params);
			else
				$reg->loadINI($detail->params);
			$params = $reg->toObject();
			$params2 = $reg->toArray();
			
			$db->setQuery("SELECT * FROM `#__rsmail_config`");
			$rsmailConfigDb = $db->loadObjectList();
			$rsmailConfig = array();
			foreach ($rsmailConfigDb as $rowConfig)
				$rsmailConfig[$rowConfig->ConfigName] = $rowConfig->ConfigValue;
			
			if ($params->formId == $args['formId'])
			{
				//get the submission details
				$db->setQuery("SELECT FieldName , FieldValue FROM #__rsform_submission_values WHERE FormId = ".(int) $args['formId']." AND SubmissionId = ".(int) $args['SubmissionId']);
				$submissions = $db->loadObjectList();
				
				$result = array();
				foreach ($submissions as $submission)
					$result[$submission->FieldName] = $submission->FieldValue;
				
				//get the email address				
				$elements = array_flip($params2);
				$emailElement = $elements['RSM_EMAIL'];
				$email = $result[$emailElement];
								
				if (isset($result['RSMail_component']))
				{						
					$db->setQuery("SELECT COUNT(IdSubscriber) FROM #__rsmail_subscribers WHERE IdList = ".(int) $detail->IdList." AND SubscriberEmail = '".$db->getEscaped($email)."'");
					$alreadySubscribed = $db->loadResult();
					
					if ($alreadySubscribed == 0)
					{
						//set the status of the subscriber
						$published = 0;
						$published = ($rsmailConfig['confirm_email'] == 0) ? 1 : 0;
						
						//lets add the subscriber into RSMail!
						$db->setQuery("INSERT INTO #__rsmail_subscribers SET SubscriberEmail = '".$db->getEscaped($email)."' , IdList = ".(int) $detail->IdList." , DateSubscribed = ".time()." , UserId = ".(int) $userid." , SubscriberIp = '".$db->getEscaped($_SERVER['REMOTE_ADDR'])."' , published = ".$published);
						$db->query();
						$subscriberId = $db->insertid();
						
						foreach ($params as $prop => $param)
						{
							if($param == JText::_('RSM_IGNORE')) continue;
							if($param == JText::_('RSM_EMAIL')) continue;
							if($prop == 'formId') continue;
							
							$db->setQuery("INSERT INTO #__rsmail_subscriber_details SET IdSubscriber = ".(int) $subscriberId." , IdList = ".(int) $detail->IdList." , FieldName = '".$db->getEscaped($param)."' , FieldValue = '".$db->getEscaped($result[$prop])."' ");
							$db->query();
						}
						
						$db->setQuery("SELECT ListName FROM #__rsmail_lists WHERE IdList = ".(int) $detail->IdList);
						$listName = $db->loadResult();
						
						//send the confirmation email 
						if ($published == 0)
						{
							$to			= $email;
							$from		= $rsmailConfig['confirm_from'];
							$fromName	= $rsmailConfig['confirm_fromname'];
							$subject 	= $rsmailConfig['confirm_subject'];
							$type		= $rsmailConfig['confirm_type'];
							$db->setQuery("SELECT `text` FROM #__rsmail_emails WHERE `type` = 'confirmation' AND lang = '".$db->getEscaped($tag)."' ");
							$message	= $db->loadResult();
							
							$secret = md5($detail->IdList.$subscriberId.$db->getEscaped($email));
							$secretLink = '<a href="'.JURI::root().'index.php?option=com_rsmail&task=activate&secret='.$secret.'">'.JText::_('RSM_CLICK_TO_ACTIVATE').'</a>';
							
							$bad	= array('{newsletter}','{email}','{activationlink}');
							$good	= array($listName,$to,$secretLink);
							
							$subject = str_replace($bad,$good,$subject);
							$message = str_replace($bad,$good,$message);
							
							JUtility::sendMail($from ,$fromName, $to, $subject, $message, $type);
						}
						
						
						//send notifications
						if ($rsmailConfig['enable_notifications'])
						{
							jimport('joomla.mail.helper');
							$emails = trim($rsmailConfig['notification_emails']);
							if (!empty($emails))
							{
								$emails = explode(',',$emails);
								if (!empty($emails))
								{
									$from	  = $config->getValue('config.mailfrom');
									$fromName = $config->getValue('config.fromname');
									$subject  = JText::sprintf('RSM_NOTIFICATION_SUBJECT',$listName);
									
									foreach ($emails as $e_mail)
									{
										if (JMailHelper::isEmailAddress($e_mail))
										{
											$user_details[] = JText::_('RSM_EMAIL').': '.$email;
											if(!empty($params2))
											foreach($params2 as $prop => $value)
											{
												if (empty($value)) continue;
												if ($value == JText::_('RSM_IGNORE')) continue;
												if ($value == 'RSM_IGNORE') continue;
												if ($value == JText::_('RSM_EMAIL')) continue;
												if ($value == 'RSM_EMAIL') continue;
												if ($prop == 'formId') continue;
												$user_details[] = $value.': '. $_POST['form'][$prop];
											}
											
											$details = implode('<br />',$user_details);
											$body = JText::sprintf('RSM_NOTIFICATION_MESSAGE',$listName,$details);
											JUtility::sendMail($from , $fromName , $e_mail , $subject , $body , 1);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	
	function rsfp_bk_onAfterShowComponents()
	{
		if (!$this->canRun()) return;
		
		// Load the language file
		$lang =& JFactory::getLanguage();
		$lang->load('com_rsmail', JPATH_ADMINISTRATOR );
		$lang->load('com_rsmail', JPATH_SITE);
		
		$formId = JRequest::getInt('formId');
		$components = RSFormProHelper::componentExists($formId, 25);
		$link = "displayTemplate('25')";
		if (!empty($components))
			$link = "displayTemplate('25', '".$components[0]."')";
		
		?>
		<li class="rsform_navtitle"><?php echo JText::_('RSFP_RSMAIL_COMPONENT'); ?></li>
		<li><a href="javascript: void(0);" onclick="<?php echo $link;?>;return false;" id="rsfpc25"><span id="checkboxgroup"><?php echo JText::_('RSFP_RSMAIL_LABEL'); ?></span></a></li>
		<?php
	}
	
	function rsfp_bk_onBeforeCreateFrontComponentBody($args)
	{
		$lang =& JFactory::getLanguage();
		$lang->load( 'com_rsmail',JPATH_ADMINISTRATOR );
		$lang->load( 'com_rsmail',JPATH_SITE );
	}
	
	function createSubscribeOption()
	{
		// Load the language file
		$lang =& JFactory::getLanguage();
		$lang->load('com_rsmail', JPATH_ADMINISTRATOR );
		$lang->load('com_rsmail', JPATH_SITE);
		
		return '1|'.JText::_('RSM_SUBSCRIBE_NAME');
	}
}